package com.finder.im.server.friendship.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.finder.im.common.ResponseVO;
import com.finder.im.common.enums.AllowFriendTypeEnum;
import com.finder.im.common.enums.CheckFriendShipTypeEnum;
import com.finder.im.common.enums.FriendShipErrorCode;
import com.finder.im.common.enums.FriendShipStatusEnum;
import com.finder.im.server.friendship.dao.ImFriendShipEntity;
import com.finder.im.server.friendship.dao.mapper.ImFriendShipMapper;
import com.finder.im.server.friendship.model.req.*;
import com.finder.im.server.friendship.model.resp.CheckFriendShipResp;
import com.finder.im.server.friendship.model.resp.ImportFriendShipResp;
import com.finder.im.server.friendship.service.ImFriendService;
import com.finder.im.server.user.dao.ImUserDataEntity;
import com.finder.im.server.user.service.ImUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class ImFriendServiceImpl implements ImFriendService {

    @Autowired
    ImFriendShipMapper imFriendShipMapper;

    @Autowired
    ImUserService imUserService;

    @Override
    public ResponseVO importFriendShip(ImportFriendShipReq req) {
        //检查参数
        if (req.getFriendItem().size() > 100) {
            //todo 返回提示
        }

        ImportFriendShipResp resp = new ImportFriendShipResp();
        List<String> successId = new ArrayList<>();
        List<String> failId = new ArrayList<>();

        //遍历导入数据
        for (ImportFriendShipReq.ImportFriendDto dto : req.getFriendItem()) {
            ImFriendShipEntity friendShip = new ImFriendShipEntity();
            BeanUtils.copyProperties(dto, friendShip);
            friendShip.setAppId(req.getAppId());
            friendShip.setFromId(req.getFromId());
            try {
                int insert = imFriendShipMapper.insert(friendShip);
                if (insert == 1) {
                    successId.add(dto.getToId());
                } else {
                    failId.add(dto.getToId());
                }
            } catch (Exception e) {
                e.printStackTrace();
                failId.add(dto.getToId());
            }
        }

        resp.setErrorId(failId);
        resp.setSuccessId(successId);

        return ResponseVO.successResponse(resp);
    }

    @Override
    public ResponseVO addFriend(AddFriendReq req) {
        //检查两个用户记录已经存在
        ResponseVO<ImUserDataEntity> fromUser = imUserService.getSingleUserInfo(req.getFromId(), req.getAppId());
        if (!fromUser.isOk()) {
            return fromUser;
        }


        ResponseVO<ImUserDataEntity> toUser = imUserService.getSingleUserInfo(req.getToItem().getToId(), req.getAppId());
        if (!toUser.isOk()) {
            return toUser;
        }
        ImUserDataEntity data = toUser.getData();
        //校验好友添加方式
        if (data.getFriendAllowType() != null && data.getFriendAllowType() == AllowFriendTypeEnum.NOT_NEED.getCode()) {
            //无需验证，添加好友方法
            return this.doAddFriend(req.getFromId(), req.getToItem(), req.getAppId());
        } else {
            //需要验证
        }

        return null;


    }

    @Override
    public ResponseVO updateFriend(UpdateFriendReq req) {
        //检查两个用户记录已经存在
        ResponseVO<ImUserDataEntity> fromUser = imUserService.getSingleUserInfo(req.getFromId(), req.getAppId());
        if (!fromUser.isOk()) {
            return fromUser;
        }


        ResponseVO<ImUserDataEntity> toUser = imUserService.getSingleUserInfo(req.getToItem().getToId(), req.getAppId());
        if (!toUser.isOk()) {
            return toUser;
        }

        return this.doUpdateFriend(req.getFromId(), req.getToItem(), req.getAppId());
    }

    @Override
    public ResponseVO deleteFriend(DeleteFriendReq req) {
        //查询存在好友关系
        QueryWrapper<ImFriendShipEntity> query = new QueryWrapper<>();
        query.eq("app_id", req.getAppId());
        query.eq("from_id", req.getFromId());
        query.eq("to_id", req.getToId());
        ImFriendShipEntity fromItem = imFriendShipMapper.selectOne(query);
        if (fromItem == null) {
            //不存在好友关系
            return ResponseVO.errorResponse(FriendShipErrorCode.TO_IS_NOT_YOUR_FRIEND);
        } else {
            if (fromItem.getStatus() == FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode()) {
                //存在好友关系且已经添加，则修改为未添加
                ImFriendShipEntity update = new ImFriendShipEntity();
                update.setStatus(FriendShipStatusEnum.FRIEND_STATUS_DELETE.getCode());
                imFriendShipMapper.update(update, query);
            } else {
                return ResponseVO.successResponse(FriendShipErrorCode.FRIEND_IS_DELETED);
            }
        }

        return ResponseVO.successResponse();
    }

    @Override
    public ResponseVO deleteAllFriend(DeleteFriendReq req) {
        QueryWrapper<ImFriendShipEntity> query = new QueryWrapper<>();
        query.eq("app_id", req.getAppId());
        query.eq("from_id", req.getFromId());
        query.eq("status", FriendShipStatusEnum.FRIEND_STATUS_NORMAL);
        ImFriendShipEntity friendShip = new ImFriendShipEntity();
        friendShip.setStatus(FriendShipStatusEnum.FRIEND_STATUS_NO_FRIEND.getCode());
        imFriendShipMapper.update(friendShip, query);//查询所有满足的记录，并执行更新
        return ResponseVO.successResponse();
    }

    @Override
    public ResponseVO getAllFriendShip(GetAllFriendShipReq req) {
        QueryWrapper<ImFriendShipEntity> query = new QueryWrapper<>();
        query.eq("app_id", req.getAppId());
        query.eq("from_id", req.getFromId());
        List<ImFriendShipEntity> friendShipEntityList = imFriendShipMapper.selectList(query);
        return ResponseVO.successResponse(friendShipEntityList);
    }

    @Override
    public ResponseVO getRelation(GetRelationReq req) {
        QueryWrapper<ImFriendShipEntity> query = new QueryWrapper<>();
        query.eq("app_id", req.getAppId());
        query.eq("from_id", req.getFromId());
        query.eq("to_id", req.getToId());

        ImFriendShipEntity friendShip = imFriendShipMapper.selectOne(query);
        if (friendShip == null) {
            return ResponseVO.errorResponse(FriendShipErrorCode.REPEATSHIP_IS_NOT_EXIST);
        }

        return ResponseVO.successResponse(friendShip);
    }

    @Override
    public ResponseVO checkBlack(CheckFriendShipReq req) {

        Map<String, Integer> toIdMap = req.getToIds().stream().collect(Collectors.toMap(Function.identity(), e -> 0));

        List<CheckFriendShipResp> result = new ArrayList<>();

        if (req.getCheckType() == CheckFriendShipTypeEnum.SINGLE.getType()) {
            result = imFriendShipMapper.checkFriendShip(req);
        } else {
            //TODO 模式2 双方校验
            result = imFriendShipMapper.checkFriendShipBoth(req);
        }

        Map<String, Integer> collect = result.stream().collect(Collectors.toMap(CheckFriendShipResp::getToId, CheckFriendShipResp::getStatus));

        //对于没有记录的手动进行填充
        for (String toId : toIdMap.keySet()) {
            if (!collect.containsKey(toId)) {
                CheckFriendShipResp checkFriendShipReq = new CheckFriendShipResp();
                checkFriendShipReq.setFromId(req.getFromId());
                checkFriendShipReq.setToId(toId);
                checkFriendShipReq.setStatus(collect.get(toId));
                result.add(checkFriendShipReq);
            }
        }

        return ResponseVO.successResponse(result);
    }


    @Transactional
    public ResponseVO doUpdateFriend(String fromId, FriendDto dto, Integer appId) {
        UpdateWrapper<ImFriendShipEntity> updateWrapper = new UpdateWrapper<>();
        updateWrapper.lambda().set(ImFriendShipEntity::getRemark, dto.getRemark())
                .set(ImFriendShipEntity::getExtra, dto.getExtra())
                .eq(ImFriendShipEntity::getAppId, appId)
                .eq(ImFriendShipEntity::getFromId, fromId)
                .eq(ImFriendShipEntity::getToId, dto.getToId());

        imFriendShipMapper.update(null, updateWrapper);

        return ResponseVO.successResponse();
    }

    @Transactional
    public ResponseVO doAddFriend(String fromId, FriendDto dto, Integer appId) {
        //A-B
        //Friend表插入A 和 B 两条记录
        //查询是否有记录存在，如果存在则判断状态，如果是已添加，则提示已添加，如果是未添加，则修改状态

        QueryWrapper<ImFriendShipEntity> query = new QueryWrapper<>();
        query.eq("app_id", appId);
        query.eq("from_id", fromId);
        query.eq("to_id", dto.getToId());
        ImFriendShipEntity friendShip = imFriendShipMapper.selectOne(query);
        //判断是否存在记录
        if (friendShip == null) {
            //不存在好友关系
            friendShip = new ImFriendShipEntity();
            friendShip.setFromId(fromId);
            friendShip.setAppId(appId);
            BeanUtils.copyProperties(dto, friendShip);
            //更新添加状态
            friendShip.setStatus(FriendShipStatusEnum.BLACK_STATUS_NORMAL.getCode());
            friendShip.setCreateTime(System.currentTimeMillis());
            int insert = imFriendShipMapper.insert(friendShip);
            if (insert != 1) {
                return ResponseVO.errorResponse(FriendShipErrorCode.ADD_FRIEND_ERROR);
            }
        } else {
            //如果存在则判断状态，如果是已添加，则提示已添加，如果是未添加，则修改状态
            if (friendShip.getStatus() == FriendShipStatusEnum.BLACK_STATUS_NORMAL.getCode()) {
                return ResponseVO.errorResponse(FriendShipErrorCode.TO_IS_YOUR_FRIEND);
            } else {
                ImFriendShipEntity update = new ImFriendShipEntity();
                if (StringUtils.isNotBlank(friendShip.getAddSource())) {
                    update.setAddSource(friendShip.getAddSource());
                }

                if (StringUtils.isNotBlank(friendShip.getRemark())) {
                    update.setRemark(friendShip.getRemark());
                }

                if (StringUtils.isNotBlank(friendShip.getExtra())) {
                    update.setExtra(friendShip.getExtra());
                }

                update.setStatus(FriendShipStatusEnum.FRIEND_STATUS_NORMAL.getCode());

                int result = imFriendShipMapper.update(update, query);
                if (result != 1) {
                    return ResponseVO.errorResponse(FriendShipErrorCode.ADD_FRIEND_ERROR);
                }
            }
        }
        return ResponseVO.successResponse();
    }
}
